#include "GvCodeTask.h"

GvCodeTask::GvCodeTask(char* body, int client_fd, int len, int shmid, int msgid) :BaseTask(body, client_fd, len, shmid, msgid)
{
	
}

void GvCodeTask::working()
{
	cout << "------发送图形验证码................" << endl;
	ShmControl* shm = (ShmControl*)shmat(shmid, NULL, 0);
	int index = -1;//空闲下标
	// 寻找下一个空闲块（状态0）
	for (int i = 0; i < MEMORYNUMBER; i++) {
		int status = shm->blocks[i].status;
		if (status == 0) { // 空闲
			index = i;
			break;
		}
	}
	GV_CODE_RESP code_resp = { 0 };
	HEAD head = { 0 };
	//随机生成一个验证码
	string code = VerifyCode();
	char send[MEMORYSIZE] = { 0 };
	//写入map保存
	Codemap[client_fd] = code;
	//写头
	head.data_len = sizeof(GV_CODE_RESP);
	head.service_type = GV_CODE;
	head.index = 1;
	head.checksum = 100;
	//写体
	strcpy(code_resp.code,code.c_str());
	code_resp.status_code = Success;
	strcpy(code_resp.message,"图形验证码：已发送");
	//头体结合
	memcpy(send, &head, sizeof(HEAD));
	memcpy(send + sizeof(HEAD), &code_resp, sizeof(GV_CODE_RESP));
	//写入共享内存
	ShmBlock* block = &shm->blocks[index];
	memcpy(block->data, send, sizeof(block->data));//考入共享内存
	block->status = 1;                   // 标记为已写
	shmdt(shm);
	//写入消息队列
	MSG msg = { 0 };
	msg.client_fd = client_fd;
	msg.index = index;
	msg.mtype = 1;
	msgsnd(msgid, &msg, sizeof(MSG), 0);
	cout << "------图形验证码已发送--------------" << endl;
}

string GvCodeTask::VerifyCode()
{
	std::string code;
	srand(time(nullptr)); // 初始化随机数种子

	for (int i = 0; i < 4; ++i)
	{
		int digit = rand() % 10; // 生成 0-9 的随机数字
		code += std::to_string(digit); // 将数字转换为字符串并追加到 code
	}
	return code;
}